package com.kancy.stream.rabbit.message;

import com.kancy.stream.rabbit.annotation.ChannelKey;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * AbstractChannelMessage
 *
 * @author kancy
 * @date 2020/3/8 16:46
 */
public abstract class AbstractChannelMessage<T> extends ChannelMessage<T> {

    /**
     * 缓存这个值，避免每次解析
     */
    private static Map<Class<? extends AbstractChannelMessage>, String> channelKeyCache = new HashMap<>();

    /**
     * 消息渠道配置对应的key
     *
     * @return
     */
    @Override
    public String getChannelKey() {
        if (!channelKeyCache.containsKey(this.getClass())){
            synchronized (channelKeyCache){
                if (!channelKeyCache.containsKey(this.getClass())){
                    initKey();
                }
            }
        }
        return channelKeyCache.get(this.getClass());
    }

    /**
     * 初始化
     */
    private void initKey() {
        String channelKey = null;
        // 用注解的方式
        ChannelKey annotation = this.getClass().getDeclaredAnnotation(ChannelKey.class);
        if (Objects.nonNull(annotation)){
            channelKey = annotation.value();
        }
        if (Objects.isNull(channelKey) || channelKey.trim().isEmpty()){
            throw new IllegalStateException(String.format("ChannelMessage [%s] channel key is empty", this.getClass().getName()));
        }
        channelKeyCache.put(this.getClass(), channelKey);
    }
}
